<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 1. 创建websocket实例
      const ws = new WebSocket('ws://localhost:8080')

      // 监听连接状态
      ws.onopen = function (event) {
        console.log('连接成功...')
        // 向服务器发送消息
        ws.send('Hello, Server!')
      }

      // 监听关闭连接
      ws.onclose = function (event) {
        console.log('断开连接...')
        ws.send('Bye Server!')
      }

      // 监听消息
      ws.onmessage = function (event) {
        // 服务器数据可能是文本，也可能是二进制数据
        const data = event.data
        if (typeof data === 'string') {
          console.log('data is ' + data)
        } else if (data instanceof ArrayBuffer) {
          console.log('data is arrayBuffer' + data.byteLength)
        }
      }

    </script>
  </body>
</html>
